package net.lzzy.practicesapi1.handlers;

import lombok.Getter;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;


/**
 * @author Administrator
 * 说明：如果一个类仅对另一个类有用，那么就将其嵌入到另一个类中；这样可以使程序包更简洁，代码更具有可阅读性，类也更靠近使用位置
 * 非static的，一般是要访问外部类的成员，，初始化就需要外部类的实例，handler.new ExceptionWrapper()
 * static的嵌套类，可以直接实例化，无需外部对象
 */
@RestControllerAdvice(annotations = RestController.class)
public class ApiExceptionHandler {
    @Getter
    public static class ExceptionWrapper{
        private  final String desc;
        private  final String message;
        private  final StackTraceElement[] elements;

        public ExceptionWrapper(String desc, String message, StackTraceElement[] elements) {
            this.desc = desc;
            this.message = message;
            this.elements = elements;
        }
    }
    @ExceptionHandler(BusinessException.class)
    public ExceptionWrapper businessHandler(WebRequest request, Exception e){
        return new ExceptionWrapper(request.getDescription(true), e.getMessage(), e.getStackTrace());
    }

    /**
     * 拦截控制器中没有被捕获的异常
     * @param request  requestWebRequest对象,包装了HttpServletRequst和HttpServletRespanse
     * @param e 异常对象
     * @return 返回自定义的异常对象
     */
    @ExceptionHandler(Exception.class)
    public ExceptionWrapper handler(WebRequest request, Exception e){
        return new ExceptionWrapper(request.getDescription(true), e.getMessage(), e.getStackTrace());
    }
}
